<template>
  <div>
    <div class="header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home/overallDisplay' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="search">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="输入搜索">
          <el-input v-model="formInline.idOrName" placeholder="请输入编号或用户名"></el-input>

        </el-form-item>
        <el-form-item>

          <el-button icon="el-icon-search" @click="onsubmit">搜索</el-button>

          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="add">
      <i class="el-icon-s-order" style="float: left;"><span>数据列表</span></i>
      <el-button style="float: right;" @click="dialogTableVisible = true">增加</el-button>
      <el-dialog title="添加角色" :visible.sync="dialogTableVisible" :lock-scroll="false" :modal="false">
        <el-form :model="addform" :rules="rules" ref="ruleForm">
          <el-form-item label="角色名称" prop="name" :label-width="formLabelWidth">
            <el-input v-model="addform.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
            <el-input v-model="addform.remark" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="code" :label-width="formLabelWidth">
            <el-select v-model="addform.code" placeholder="请选择权限">
              <el-option label="test" value="test"></el-option>
              <el-option label="normal" value="normal"></el-option>
              <el-option label="root" value="root"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用" :label-width="formLabelWidth">
            <el-radio v-model="addform.status" label="1">是</el-radio>
            <el-radio v-model="addform.status" label="0">否</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('ruleForm')">取消</el-button>
          <el-button type="primary" @click="addRole('ruleForm')">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="form">
      <el-table :data="tableData" border style="width: 100%" height="400">
        <el-table-column fixed prop="id" label="编号" min-width="100"></el-table-column>
        <el-table-column prop="name" label="用户名" min-width="120"></el-table-column>
        <el-table-column prop="code" label="权限" min-width="120"></el-table-column>
        <el-table-column prop="remark" label="描述" min-width="150"></el-table-column>
        <el-table-column prop="userCount" label="用户数" min-width="120"></el-table-column>
        <el-table-column prop="addtime" label="添加时间" min-width="300"></el-table-column>
        <el-table-column label="是否启用" min-width="120">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isEnabled" :active-value="1" :inactive-value="0" active-color="#13ce66"
              inactive-color="#ff4949" @change="handleSwitchChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="150">
          <template slot-scope="scope">
            <!-- <el-button type="text" size="small" @click="roleDialogVisible = true">分配角色</el-button>
            <el-dialog title="分配角色" :visible.sync="roleDialogVisible" :lock-scroll="false" :modal="false">
              <el-form :model="roleForm">
                <el-form-item label="选择角色">
                  <el-select v-model="roleForm.selectedRole" placeholder="请选择角色">
                    <el-option label="角色一" value="role1"></el-option>
                    <el-option label="角色二" value="role2"></el-option>
                    <el-option label="角色三" value="role3"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="roleDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAssignRole(scope.row, roleForm.selectedRole)">确定</el-button>
              </div>
            </el-dialog> -->

            <el-button type="text" @click="editUser(scope.row)">编辑</el-button>
            <el-dialog title="编辑角色" :visible.sync="editTableVisible" :lock-scroll="false" :modal="false">
              <el-form :model="editform">
                <el-form-item label="用户名" :label-width="formLabelWidth">
                  <el-input v-model="editform.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="权限" :label-width="formLabelWidth">
            <el-select v-model="editform.code" placeholder="请选择权限">
              <el-option label="test" value="test"></el-option>
              <el-option label="normal" value="normal"></el-option>
              <el-option label="root" value="root"></el-option>
            </el-select>
          </el-form-item>
                <el-form-item label="描述" :label-width="formLabelWidth">
                  <el-input v-model="editform.remark" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="是否启用" :label-width="formLabelWidth">
                  <el-radio v-model="editform.status" label="1">是</el-radio>
                  <el-radio v-model="editform.status" label="0">否</el-radio>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="editTableVisible = false">取消</el-button>
                <el-button type="primary" @click="updateRole('ruleForm')">确定</el-button>
              </div>
            </el-dialog>

            <el-button type="text" @click="showDeleteDialog(scope.row.id)">删除</el-button>
<!--            <el-dialog title="提示" :visible.sync="delVisible" width="30%" :before-close="handleClose"-->
<!--              :lock-scroll="false" :modal="false">-->
<!--              <span>是否删除角色</span>-->
<!--              <span slot="footer" class="dialog-footer">-->
<!--                <el-button @click="delVisible = false">取 消</el-button>-->
<!--                <el-button type="primary" @click="handleDeleteConfirm()">确 定</el-button>-->
<!--              </span>-->
<!--            </el-dialog>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="currentPage4" :page-sizes="[5, 10, 20, 30]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: "UserList",
  data() {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('角色名称不能为空'));
      } else {
        callback();
      }
    };
    var validateRemark = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('备注不能为空'));
      } else {
        callback();
      }
    };
    var validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('code不能为空'));
      } else {
        callback();
      }
    };
    return {
      formInline: {
        idOrName: ''
      },
      visible: false,
      currentPage4: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      roleNumber: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      editTableVisible: false,
      delVisible: false,
      selectedId: null,
      radio: '1',
      addform: {
        name: '',
        remark: '',
        code: '',
        status: '1'
      },
      rules:{
        name:[
          { validator: validateName, trigger: 'blur' }
        ],
        remark:[
          { validator: validateRemark, trigger: 'blur' }
        ],
        code:[
          { validator: validateCode, trigger: 'blur' }
        ]
      },
      editform: {
        id: '',
        name: '',
        code: '',
        remark: '',
        status: '1'
      },
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '120px',
      roleDialogVisible: false,
      roleForm: {
        selectedRole: ''
      }
    }
  },
  mounted() {
    this.fetchRoleList();
    this.fetchRoleNumbers();
  },
  methods: {
    fetchRoleList() {
      return axios.get('http://localhost:8080/home/roleList', {
        params: {
          page: this.currentPage4,
          size: this.pageSize,
          idOrName: this.formInline.idOrName
        }
      })
        .then(response => {
          console.log('获取角色列表成功:', response.data);
          const allRoleData = response.data.data.allRole.map(role => ({
            id: role.id,
            name: role.name,
            code: role.code,
            remark: role.remark,
            userCount: role.userCount,
            addtime: role.updated,
            isEnabled: role.status,
            roleDialogVisible: false,

          }));
          const startIndex = (this.currentPage4 - 1) * this.pageSize;
          const endIndex = startIndex + this.pageSize;
          this.tableData = allRoleData.slice(startIndex, endIndex);
          this.total = response.data.data.allRole.length;

          this.fetchRoleNumbers(); // 获取用户数数据

          console.log(this.total);
        })
        .catch(error => {
          console.error('获取角色列表失败:', error);
        });
    },
    fetchRoleNumbers() {
      axios.get('http://localhost:8080/home/roleList')
        .then(response => {
          console.log('获取到的用户数量数据:', response.data);
          if (response.data && response.data.data && response.data.data.roleNumber) {
            this.roleNumber = response.data.data.roleNumber;
            this.mergeUserCounts();
          } else {
            console.warn('响应数据中未找到 roleNumber 字段');
            this.roleNumber = [];
          }
        })
        .catch(error => {
          console.error('获取用户数量失败:', error);
        });
    },
    mergeUserCounts() {
      const roleNumberMap = this.roleNumber.reduce((acc, item) => {
        const [roleName, count] = Object.entries(item)[0];
        acc[roleName] = count;
        return acc;
      }, {});

      this.tableData = this.tableData.map(role => ({
        ...role,
        userCount: roleNumberMap[role.name] || 0
      }))
    },
    onsubmit() {
      const { idOrName } = this.formInline;
      const currentPage = this.currentPage4;
      if (!idOrName || idOrName.trim() === '') {
        this.$message.warning('请输入有效的搜索条件'); // 提示用户输入条件
        return; // 直接返回，不执行后续逻辑
      }else{

        console.log(idOrName);
      }


      axios.post("http://localhost:8080/home/queryRole", null, {
        params: {
          idOrName: idOrName
        }
      }).then(response => {
        console.log('搜索成功:', response.data);
        if (response.data.code === 20000 && response.data.data.qureyRole) {
          let qureyRole = response.data.data.qureyRole;
          if (!Array.isArray(qureyRole)) {
            qureyRole = [qureyRole];
          }
          this.total = qureyRole.length;
          console.log(this.total);
          const totalPages = Math.ceil(this.total / this.pageSize);
          if (currentPage > totalPages) {
            this.currentPage4 = totalPages || 1;
          } else {
            this.currentPage4 = currentPage;
          }
          this.tableData = qureyRole.map(role => ({
            id: role.id,
            name: role.name,
            code: role.code,
            remark: role.remark,
            userCount: role.userCount || 0,
            addtime: role.updated,
            isEnabled: role.status
          })), this.fetchRoleNumbers();
          this.$message({
            message:'搜索成功',
            type:'success'
          });
        } else {
          this.tableData = [];
          this.$message.error('未找到相关角色');
          this.currentPage4 = 1;
        }
      })
        .catch(error => {
          console.error('搜索失败:', error);
          this.$message.error('搜索失败，请重试');
        });
    },
    resetForm() {
      this.formInline.idOrName = '';
      this.tableData = this.fetchRoleList();
      this.currentPage4 = 1;

    },
    resetAddForm() {
      this.addform.name = '';
      this.addform.remark = '';
      this.addform.code = '';
      this.addform.status;
    },
    handleSwitchChange(row){
      console.log(row.isEnabled)
      const id=row.id
      const isEnabled=row.isEnabled
      axios.post("http://localhost:8080/home/updatedRoleStatus",{
      "status":isEnabled,
        "id":id
      }
      ).then((res)=>{
        console.log(res)
      })
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage4 = 1;
      this.fetchRoleList();
    },
    handleCurrentChange(page) {
      this.currentPage4 = page;
      this.fetchRoleList();
    },

    handleAssignRole(row, selectedRole) {
      console.log('Assign role:', selectedRole, 'to user:', row);
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done();
        })
        .catch(() => { });
    },
    addRole(formName) {
      console.log('添加角色:', this.addform);
      // 发送请求到后端

      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post('http://localhost:8080/home/addRole', {
            "name": this.addform.name,
            "remark": this.addform.remark,
            "code": this.addform.code,
            "status": this.addform.status
          })
              .then(response => {
                console.log('添加角色成功:', response.data);
                this.$message.success('添加角色成功');
                this.fetchRoleList();
                // 刷新表单内容
                this.resetAddForm();
              })
              .catch(error => {
                console.error('添加角色失败:', error);
                this.$message.error('添加角色失败');
              });

          // 关闭对话框
          this.dialogTableVisible = false;
          this.$store.dispatch('productForm/SET_first_DATA', this.addform)
        } else {
          console.log('error submit!!!');
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogTableVisible = false;
      this.$refs[formName].resetFields();
    },
    editUser(row) {
      this.editform = {
        id: row.id,
        name: row.name,
        code: row.code,
        remark: row.remark,
        status: row.isEnabled ? '1' : '0'
      };
      this.editTableVisible = true;
    },
    updateRole() {
      console.log('更新角色:', this.editform);
      // 发送请求到后端
      axios.post('http://localhost:8080/home/upRole', {
        "id": this.editform.id,
        "name": this.editform.name,
        "remark": this.editform.remark,
        "code": this.editform.code,
        "status": this.editform.status === '1' ? 1 : 0
      }
        // , {
        //   headers: {
        //     'Content-Type': 'application/json'
        //   }
        // }
      )
        .then(response => {
          console.log('更新角色成功:', response.data);
          this.$message.success('更新角色成功');
          this.fetchRoleList();
        })
        .catch(error => {
          console.error('更新角色失败:', error);
          this.$message.error('更新角色失败');
        });


      // 关闭对话框
      this.editTableVisible = false;
    },
    showDeleteDialog(id) {
      this.$confirm('确定要删除选中的项目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.selectedId = id;
        this.handleDeleteConfirm()
        this.$message({
          type: 'success',
          message: `成功删除`
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDeleteConfirm() {
      // 发送删除请求
      axios.post('http://localhost:8080/home/deleteRole', null, { params: { id: this.selectedId } })
        .then(response => {
          console.log('删除成功:', response.data);
          // 重新获取角色列表
          // this.fetchRoleList();
          // 重新获取角色列表
          this.fetchRoleList().then(() => {
            if (this.tableData.length === 0 && this.currentPage4 > 1) {
              this.currentPage4--; // 如果当前页面无数据，且不在第一页，则回退到上一页
              this.fetchRoleList(); // 再次获取用户列表
            }
          });
        })
    }


  }
}


</script>

<style scoped>
.form {
  width: 100%;
  overflow-x: auto;
}

.el-table {
  margin-bottom: 20px;
}

.header {
  width: 100%;
  padding-bottom: 20px;
}

.search {
  width: 100%;
  padding-bottom: 20px;
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 5px;
}

.add {
  width: 100%;
  padding-bottom: 20px;
  overflow: hidden;
}

.block {
  margin-top: 20px;
}
</style>
